package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.sys.core.exception.BusException;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.core.exception.enums.BusExceptionEnum;
import cn.stylefeng.guns.sys.core.properties.GzhConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.WxMsgPushEnum;
import cn.stylefeng.guns.sys.modular.system.entity.WxmsgPush;
import cn.stylefeng.guns.sys.modular.system.model.params.WxmsgPushParam;
import cn.stylefeng.guns.sys.modular.system.model.weixin.SendMsgResult;
import cn.stylefeng.guns.sys.modular.system.model.weixin.TemplateData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.util.List;

/**
 * 微信推送模板消息服务类
 * @author gyz
 */
@Service
public class WeChatSendTempMsgService {
    private static final Logger log= LoggerFactory.getLogger(WeChatSendTempMsgService.class);

    private static final String URL_SENDMSG="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    private static final String TEMPID ="GvxDqRmFMg41dT9-0ndOF6oh8_XW_Vcx0mXO04m6PNQ";
//    private static final String TEMPID ="0aFG_thWS9tFY17Vi8cLjjwtWELpC081rhSaw_gt-3U";
    private static final String WXTEMPID ="soo66quSNt3J8wFa2Yr4sPvoYUJzrY7pmR_Y92xpkZY";
//    private static final String APPID ="wx0215c6330cc918bf";
        private static final String APPID ="wx4356631c4f475de8";
    private static final String PAGEPATH ="pages/index/index";
    @Resource
    private DictService dictService;
    @Resource
    private GzhConfig gzhConfig;
    @Resource
    private WxmsgPushService wxmsgPushService;


    /**
     * 发送微信模板消息
     * @param openids 接受消息的openid数组
     * @param jumpUrl 需要跳转的路径
     * @param tempObj 需要传递的参数
     */
    public void sendmsg(String[] openids,String jumpUrl,JSONObject tempObj){
        //测试数据不推送消息
        TemplateData first= (TemplateData) ((JSONObject)tempObj.get("data")).get("first");
        if(first.getValue().contains("测试")){
            return;
        }

        RestTemplate restTemplate = new RestTemplate();
        //String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx0d04611c4cc1cc65&secret=89770151fbdf4cf58d2d32cf9baea547";
//        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhConfig.getAppid() + "&secret=" + gzhConfig.getSecret();
//        String content = restTemplate.getForObject(url, String.class);
//        JSONObject jsonObject = JSONObject.parseObject(content);
//        String accessToken = jsonObject.get("access_token")==null?"":jsonObject.get("access_token").toString();
//        System.out.println("accessToken:"+accessToken);

        //获取token
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }else{
            log.error("微信推送消息失败：‘获取token失败’");
            return;
        }

//        tempObj.put("template_id",TEMPID);
        //tempObj.put("template_id","KNj1YDXVVyLpcYM6susiV5x9SPz3qcvkxccDYkVP_b8");
        tempObj.put("template_id",gzhConfig.getMbid());
        if(ToolUtil.isNotEmpty(jumpUrl)){
            tempObj.put("url",jumpUrl);
        }
        if(ToolUtil.isEmpty(openids)){
            log.error("openids为空...");
            return;
        }

         //accessToken="46_Kk5WaSdcMa8QetUUFfOkEiFJ5S-n3Ir0DmDCqzhJzE_e1EaoGwkCF_MKXwO2_j_GiV8hIkY0Q2Mn75q46iuxijQDaBbW6D3ahaMM0oWn4HgkxQ5-MLZZmj6SoyErDX55FVQzh1KsmIYeYx9EGHQdAIAYZI";

        //发送消息
        for(String openid:openids){
            tempObj.put("touser",openid);
            RestTemplate rt = new RestTemplate();
            ResponseEntity<SendMsgResult> response = rt.postForEntity(URL_SENDMSG + accessToken, tempObj, SendMsgResult.class);
//            log.debug("模板推送结果：openid：{}-{}",openid,response);
            SendMsgResult result = response.getBody();
            if(result.getErrcode()!=0){
                log.error("openid：{},发送失败,cause：{}",openid,result.getErrmsg());
//                throw new BusException(BusExceptionEnum.ERR_DEFAULT);
            }else{
                log.info("模板推送结果：openid：{}：{}",openid,result.getErrmsg());
            }
        }
    }

    public void sendmsgs(String[] openids,String jumpUrl,JSONObject tempObj){
        //测试数据不推送消息
        TemplateData first= (TemplateData) ((JSONObject)tempObj.get("data")).get("first");
        if(first.getValue().contains("测试")){
            return ;
        }
        //获取token
//        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
//        String accessToken = "";
//        if (ToolUtil.isNotEmpty(dict)) {
//            accessToken = dict.getName();
//        }else{
//            log.error("微信推送消息失败：‘获取token失败’");
//        }

        String accessToken="46_Kk5WaSdcMa8QetUUFfOkEiFJ5S-n3Ir0DmDCqzhJzE_e1EaoGwkCF_MKXwO2_j_GiV8hIkY0Q2Mn75q46iuxijQDaBbW6D3ahaMM0oWn4HgkxQ5-MLZZmj6SoyErDX55FVQzh1KsmIYeYx9EGHQdAIAYZI";


        //tempObj.put("template_id",gzhConfig.getMbid());
        tempObj.put("template_id","GvxDqRmFMg41dT9-0ndOF6oh8_XW_Vcx0mXO04m6PNQ");
//        tempObj.put("template_id",TEMPID);
        if(ToolUtil.isNotEmpty(jumpUrl)){
            tempObj.put("url",jumpUrl);
        }
        if(ToolUtil.isEmpty(openids)){
            log.error("openids为空...");
        }
        //发送消息
        for(String openid:openids){
            tempObj.put("touser",openid);
            RestTemplate rt = new RestTemplate();
            ResponseEntity<SendMsgResult> response = rt.postForEntity(URL_SENDMSG + accessToken, tempObj, SendMsgResult.class);
//            log.debug("模板推送结果：openid：{}-{}",openid,response);
            SendMsgResult result = response.getBody();
            if(result.getErrcode()!=0){
                log.error("openid：{},发送失败,cause：{}",openid,result.getErrmsg());
            }else{
                log.info("模板推送结果：openid：{}：{}",openid,result.getErrmsg());
            }
        }
    }

    /**
     * 公众号推送消息给关注用户（固定微信模板）
     *
     * @param: openids 推送的用户标识
     * @return: tempObj 模板参数
     */
    public boolean sendMessage(List<String> openids, JSONObject tempObj){
        //测试数据不推送消息
        TemplateData first = (TemplateData) ((JSONObject)tempObj.get("data")).get("first");
        if(first.getValue().contains("测试")){
            return false;
        }
        //获取token
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }else{
            log.error("微信推送消息失败：‘获取token失败’");
        }
        tempObj.put("template_id", TEMPID);
        if(ToolUtil.isEmpty(openids)){
            log.error("openids为空...");
        }
        //发送消息
        boolean sendFlag = false;
        for(String openid : openids){
            tempObj.put("touser",openid);
            RestTemplate rt = new RestTemplate();
            ResponseEntity<SendMsgResult> response = rt.postForEntity(URL_SENDMSG + accessToken, tempObj, SendMsgResult.class);
            SendMsgResult result = response.getBody();
            if(result.getErrcode()!=0){
                log.error("openid：{},发送失败,cause：{}",openid,result.getErrmsg());
            }else{
                sendFlag = true;
                log.info("模板推送结果：openid：{}：{}",openid,result.getErrmsg());
            }
        }
        return sendFlag;
    }

    /**
     * 发送微信模板消息更新内容
     * @param openids 接受消息的openid数组
     * @param jumpUrl 需要跳转的路径
     * @param tempObj 需要传递的参数
     */
    public void sendMsgUpdateContent(String[] openids,String jumpUrl,JSONObject tempObj){
        //获取token
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }else{
            log.error("微信推送消息失败：‘获取token失败’");
            return;
        }

        tempObj.put("template_id",WXTEMPID);
        if(ToolUtil.isNotEmpty(jumpUrl)){
            tempObj.put("url",jumpUrl);
        }
        if(ToolUtil.isEmpty(openids)){
            log.error("openids为空...");
            return;
        }
        //发送消息
        for(String openid:openids){
            tempObj.put("touser",openid);
            RestTemplate rt = new RestTemplate();
            ResponseEntity<SendMsgResult> response = rt.postForEntity(URL_SENDMSG + accessToken, tempObj, SendMsgResult.class);
//            log.debug("模板推送结果：openid：{}-{}",openid,response);
            SendMsgResult result = response.getBody();
            if(result.getErrcode()!=0){
                log.error("openid：{},发送失败,cause：{}",openid,result.getErrmsg());
            }else{
                log.info("模板推送结果：openid：{}：{}",openid,result.getErrmsg());
            }
        }
    }

    public void sendMsgUpdateContentByTempQuery(String[] openids, String jumpUrl, JSONArray list){
        //发送消息
        for(String openid:openids){
            //获取token
            Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
            String accessToken = "";
            if (ToolUtil.isNotEmpty(dict)) {
                accessToken = dict.getName();
            }else{
                log.error("微信推送消息失败：‘获取token失败’");
                return;
            }
            for(int i=0;i<list.size();i++){
                JSONObject tempObj = list.getJSONObject(i);

                tempObj.put("template_id",gzhConfig.getMbid_q());
                if(ToolUtil.isNotEmpty(jumpUrl)){
                    tempObj.put("url",jumpUrl);
                }
                if(ToolUtil.isEmpty(openids)){
                    log.error("openids为空...");
                    return;
                }
                tempObj.put("touser",openid);
                RestTemplate rt = new RestTemplate();
                ResponseEntity<SendMsgResult> response = rt.postForEntity(URL_SENDMSG + accessToken, tempObj, SendMsgResult.class);
//            log.debug("模板推送结果：openid：{}-{}",openid,response);
                SendMsgResult result = response.getBody();
                if(result.getErrcode()!=0){
                    log.error("openid：{},发送失败,cause：{}",openid,result.getErrmsg());
//                throw new BusException(BusExceptionEnum.ERR_DEFAULT);
                }else{
                    log.info("模板推送结果：openid：{}：{}",openid,result.getErrmsg());
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     *  设置模板消息参数
     * @param firststr first参数
     * @param remarkstr remark参数
     * @param keywords 多个keyword参数：keyword1，keyword2...
     * @return 返回设置的参数对象：json格式
     */
    public JSONObject setTempParam(String firststr,String remarkstr,String...keywords){
        TemplateData first = new TemplateData();
        first.setValue(firststr);
        TemplateData remark = new TemplateData();
        remark.setValue(remarkstr);
        remark.setColor("#ff0000");

        JSONObject dataObj = new JSONObject();
        dataObj.put("first",first);
        dataObj.put("remark",remark);
        for(int i=0;i<keywords.length;i++){
            TemplateData keyword = new TemplateData();
            keyword.setValue(keywords[i]);
            dataObj.put("keyword"+(i+1), keyword);
        }
        JSONObject tempObj = new JSONObject();
        tempObj.put("data",dataObj);
        return tempObj;
    }

    public JSONObject setTempParams(String firststr,String remarkstr,String...keywords){
        TemplateData first = new TemplateData();
        first.setValue(firststr);
        TemplateData remark = new TemplateData();
        remark.setValue(remarkstr);
        remark.setColor("#ff0000");

        JSONObject dataObj = new JSONObject();
        dataObj.put("first",first);
        dataObj.put("remark",remark);
        for(int i=0;i<keywords.length;i++){
            TemplateData keyword = new TemplateData();
            keyword.setValue(keywords[i]);
            dataObj.put("keyword"+(i+1), keyword);
        }
        //设置小程序相关参数
        JSONObject miniprogram = new JSONObject();
        miniprogram.put("appid",APPID);
        miniprogram.put("pagepath",PAGEPATH);

        JSONObject tempObj = new JSONObject();
        tempObj.put("miniprogram",miniprogram);
        tempObj.put("data",dataObj);
        return tempObj;
    }


    /**
     * 根据业务id和任务id获取需要推送的数据，并推送消息
     */
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void pushGcMessage() {
        log.info("推送微信消息开始...{}", DateUtil.getNow());
        try {
            //获取token
            Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
            String accessToken = "";
            if (ToolUtil.isNotEmpty(dict)) {
                accessToken = dict.getName();
            } else {
                log.error("微信推送消息失败：‘获取token失败’");
                return;
            }

            //获取数据
            List<WxmsgPush> results = wxmsgPushService.listToPushData(new WxmsgPushParam());
            for (WxmsgPush record : results) {
                String content = record.getMsg();
                JSONObject tempObj = JSONObject.parseObject(content);
                //测试数据不推送消息
                TemplateData first = (TemplateData) ((JSONObject) tempObj.get("data")).get("first");
                if (first.getValue().contains("测试")) {
                    return;
                }
                tempObj.put("template_id", record.getTemplateId());
                tempObj.put("touser", record.getOpenid());
                if (ToolUtil.isNotEmpty(record.getJumpUrl())) {
                    tempObj.put("url", record.getJumpUrl());
                }
                //发送消息
                RestTemplate rt = new RestTemplate();
                ResponseEntity<SendMsgResult> response = rt.postForEntity(URL_SENDMSG + accessToken, tempObj, SendMsgResult.class);
                SendMsgResult result = response.getBody();
                if (result.getErrcode() != 0) {
                    //失败
                    record.setSendResult(WxMsgPushEnum.RESULT_FAILED.getCode());
                    record.setFailMsg(result.getErrmsg());
                } else {
                    record.setSendResult(WxMsgPushEnum.RESULT_SUC.getCode());
                    record.setStatus(WxMsgPushEnum.STATUS_PUSHED.getCode());
                }
                record.setSendTimes(record.getSendTimes() + 1);
                wxmsgPushService.updateById(record);
            }

        } catch (Exception e) {
            log.error("微信推送消息异常",e);
        }
        log.info("推送微信消息结束...{}", DateUtil.getNow());
    }

}
